/**
 * 并发容器 - ConcurrentMap
 */
package concurrent.t06;

import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class Test_01_ConcurrentMap {

    public static void main(String[] args) {

        final Map<String, String> map = new Hashtable<>();   // 762毫秒
        // final Map<String, String> map = new ConcurrentHashMap<>();  // 504毫秒
        //  final Map<String, String> map = new ConcurrentSkipListMap<>();   // 700毫秒

        final Random r = new Random();// 随机数,用来随机生成map的 key--value 数据
        Thread[] array = new Thread[100];  // 100个线程
        final CountDownLatch latch = new CountDownLatch(array.length); // 100把锁的门栓

        long begin = System.currentTimeMillis();

        for (int i = 0; i < array.length; i++) {
            array[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 每个线程存10000个key-value给容器map
                    for (int j = 0; j < 10000; j++) {
                        map.put("key" + r.nextInt(100000), "value" + r.nextInt(100000));
                    }
                    latch.countDown(); // 存完后门锁减一
                }
            });
        }

        // 启动所有线程
        for (Thread t : array) {
            t.start();
        }

        // await()等待线程开放
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 线程开放后,再向下执行
        // 看100个线程,每个线程存10000次map,存100次用时时间
        long end = System.currentTimeMillis();
        System.out.println("执行时间为 ： " + (end - begin) + "毫秒！");
    }

}
